package com.kkkkkba.search.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kkkkkba.search.service.PictureService;
import com.kkkkkba.search.common.ErrorCode;
import com.kkkkkba.search.exception.BusinessException;
import com.kkkkkba.search.model.entity.Picture;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 图片服务实现类
 */
@Service
public class PictureServiceImpl implements PictureService {
    @Override
    public Page<Picture> searchPicture(String searchText, long pageNum, long pageSize) {
        long current = (pageNum - 1) * pageSize + 1;
        if(current == 1){
            pageNum  = 1;
            pageSize = 10;
            current = 10;
        }
        if(searchText == null || searchText.equals("")){
            searchText = "Java之父";
        }
        String url = String.format("https://cn.bing.com/images/search?q=%s&form=HDRSC2&first=%s",searchText,current);
//        System.out.println(url);
//        System.out.println(searchText);
        Document doc;
        try{
            doc = Jsoup.connect(url).get();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"数据获取异常");
        }
//        System.out.println(doc);
        List<Picture> list = new ArrayList<>();
        Elements newsHeadlines = doc.select(".iuscp.isv");
        for (Element headline : newsHeadlines) {
            String title = headline.select(".inflnk").get(0).attr("aria-label");
            String imgurl = headline.select(".iusc").get(0).attr("m");
            Map<String,Object> map = JSONUtil.toBean(imgurl, Map.class);
            imgurl = (String) map.get("murl");
//            System.out.println(title);
//            System.out.println(imgurl);
            list.add(new Picture(title,imgurl));
            if(list.size()>=pageSize)break;
        }
        Page<Picture> picturePage = new Page<>(pageNum,pageSize);
        picturePage.setRecords(list);
        return picturePage;
    }
}
